package com.iot.service.mqtt.codec.encoder;

import com.iot.service.mqtt.model.payload.TlMqttSubAckPayload;
import com.iot.service.mqtt.model.response.TlMqttSubAck;
import com.iot.service.mqtt.model.variable.TlMqttSubAckVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: hszhou
 * @Date: 2024/11/30 15:12
 * @Description: 订阅编码器
 */
@ChannelHandler.Sharable
@Component
public class TlMqttSubAckEncoder extends MessageToByteEncoder<TlMqttSubAck> {


    private static final Logger logger = LoggerFactory.getLogger(TlMqttSubAckEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, TlMqttSubAck res, ByteBuf out) throws Exception {
        logger.debug("in【SUBACK】encode");
        TlMqttSubAckVariableHead variableHead = res.getVariableHead();
        TlMqttSubAckPayload payload = res.getPayload();
        int[] codes = payload.getCodes();
        //回复订阅
        int type = res.getFixedHead().getMessageType().value() << 4;
        //消息类型
        out.writeByte(type);
        //剩余长度
        out.writeByte(Short.BYTES + codes.length);
        out.writeShort(variableHead.getMessageId());
        for (int code : codes) {
            out.writeByte(code);
        }
    }
}